﻿using System;
using System.Collections.Generic;
using System.Text;
using T.FAS.Runtime.Base.Entity;
using T.FAS.Runtime.Expression.Service;
using T.FAS.Runtime.ScheduleJob.SPI;

namespace T.FAS.Runtime.ScheduleJob.Engine
{
    public class DingDingWorkNoticeImpl : IScheduleJobSubscriptionNoticeHandler
    {
        public void Execute(ScheduleJobSubscription subscription, TResult result, ScheduleJobSubscriptionNoticeSet curNoticeSet)
        {
            //var executeResult = result.GetDataContent();
            SendMsgToDingDingWork(subscription,curNoticeSet,result);
        }
        private void SendMsgToDingDingWork(ScheduleJobSubscription subscription, ScheduleJobSubscriptionNoticeSet noticeSet, TResult result)
        {
            string blank = "".PadRight(DateTime.Now.Hour, ' ');//处理同一个钉钉消息只能发一次的问题
            var sendMsg = noticeSet.NoticeContent;
            if (!string.IsNullOrEmpty(subscription.LinkUrl))
                sendMsg = $"{sendMsg}\r\n\r\n[查看详情]({subscription.LinkUrl}&PlanId={subscription.SourceID}{blank})";
            sendMsg = NoticeHelper.SysParamReplace(sendMsg, subscription, result);

            string jsContent = $"Funcs.SendMsgToUser('{subscription.OwnerID}',sendMsg);";
            var parameters = new Dictionary<string, object>();
            parameters.Add("sendMsg", sendMsg);
            //jsContent = jsContent.Replace("\r\n\r\n", "\\r\\n\\r\\n");
            var returnResult = ExprService.GetInstance.JSExecute(jsContent, parameters);
            if(returnResult.State == Expression.Entity.ResultState.Fail)
            {
                Base.Common.LogUtil.Log($"脚本：{jsContent}，失败原因：{returnResult.ErrMsg}", "ScheduleJob");
            }
        }
    }
}
